package study.async.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
@RestController
public class _6_WebAsyncTaskController {

    @RequestMapping("/webAsyncTask")
    @ResponseBody
    public WebAsyncTask<Result> asyncTask() {
        log.info(">>>>>> i am controller");

        //Step-1: 定义任务
        Callable<Result> task = () -> {
            log.info(">>>>>> i am business logic");
            TimeUnit.SECONDS.sleep(3);
            return Results.ok();
        };
        //Step-2: 执行任务
        WebAsyncTask<Result> webTask = new WebAsyncTask<>(5000, task);
        //Step-3: 事件监听
        webTask.onTimeout(() -> {
            log.info("time out");
            return Results.fail();
        });
        webTask.onCompletion(() -> {
            log.info("completion");
        });
        webTask.onError(() -> {
            log.info("error");
            return Results.fail();
        });

        return webTask;
    }
}
